package com.dylan_wang.capturescreen;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class FxService extends Service {

    int timeC = 0;

    LinearLayout mFloatLayout;
    LayoutParams wmParams;

    WindowManager mWindowManager;

    SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TextView         timeTView;
    Timer            timer;
    private static final String TAG     = "秒悬浮窗FxService->";
    private static final int    SETTIME = 0;

    @Override
    public void onCreate() {

        super.onCreate();
        Log.e(TAG, "秒悬浮窗service已经进来了");

        createFloatView();
        Log.e(TAG, "创建悬浮窗执行完了");

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createFloatView() {
        wmParams = new LayoutParams();

        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0+
            wmParams.type = LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
        }
        //  wmParams.type = LayoutParams.TYPE_PHONE;

        wmParams.format = PixelFormat.RGBA_8888;

        wmParams.flags =
                // LayoutParams.FLAG_NOT_TOUCH_MODAL |
                LayoutParams.FLAG_NOT_FOCUSABLE
        // LayoutParams.FLAG_NOT_TOUCHABLE
        ;

        wmParams.gravity = Gravity.LEFT | Gravity.TOP;

        wmParams.x = 0;
        wmParams.y = 0;

        wmParams.width = LayoutParams.WRAP_CONTENT;
        wmParams.height = LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        Log.e(TAG, "这里是获取线性布局之前");
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.float_layout, null);
        Log.e(TAG, "这里是获取线性布局之后");
        mWindowManager.addView(mFloatLayout, wmParams);
        // 获取秒对象
        timeTView = (TextView) mFloatLayout.findViewById(R.id.chr);
        // 设置TV颜色大小等
        settingTView();

        Log.i(TAG, "mFloatLayout-->left" + mFloatLayout.getLeft());
        Log.i(TAG, "mFloatLayout-->right" + mFloatLayout.getRight());
        Log.i(TAG, "mFloatLayout-->top" + mFloatLayout.getTop());
        Log.i(TAG, "mFloatLayout-->bottom" + mFloatLayout.getBottom());
        // 开启定时器

        TimerTask timerTask = new TimerTask() {
            public void run() {
                Message m = new Message();
                m.what = SETTIME;
                mHandler.sendMessage(m);
                Log.e(TAG, "发送msg成功");
            }
        };

        timer = new Timer(true);
        timer.schedule(timerTask, 0, 500);

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        timeTView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                wmParams.x = (int) event.getRawX() - timeTView.getMeasuredWidth() / 2;

                Log.i(TAG, "RawX" + event.getRawX());
                Log.i(TAG, "X" + event.getX());

                wmParams.y = (int) event.getRawY() - timeTView.getMeasuredHeight() / 2 - 25;

                Log.i(TAG, "RawY" + event.getRawY());
                Log.i(TAG, "Y" + event.getY());

                mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                return false;
            }
        });
        timeTView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // String d = s.format(new java.util.Date());
                // Toast.makeText(FxService.this, "现在的时间：" + d,
                // Toast.LENGTH_SHORT).show();
            }
        });
        Log.e(TAG, "createFloatView()创建view成功了");
    }

    void settingTView() {
        Log.e(TAG, "这里是设置悬浮窗各种属性");
        // 获取本地存储对象
        SharedPreferences spSetting = getSharedPreferences("setting", MODE_PRIVATE);
        Log.e(TAG, "获取本地存储对象成功");
        // 设置颜色
        timeTView.setTextColor(Color.parseColor("#" + Integer.toHexString(spSetting.getInt("colorRed", 125)) + ""
                + Integer.toHexString(spSetting.getInt("colorGreen", 125)) + ""
                + Integer.toHexString(spSetting.getInt("colorBlue", 125))));
        // 设置大小
        timeTView.setTextSize(spSetting.getInt("textSize", 40));

        // 设置时间快慢
        timeC = spSetting.getInt("timeCorrect", 0);

    }

    private Handler mHandler = new Handler() {

        public void handleMessage(Message m) {
            Log.i(TAG, "handleMessage");
            if (m.what == SETTIME) {
                // 调整时间
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + (timeC));

                String d_ = s.format(calendar.getTime());// s.format(new
                // java.util.Date());

                timeTView.setText("" + d_);
                Log.e(TAG, "这里是handler已经接收到了信息" + d_);
            }

        }
    };

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        timer.cancel();
        if (mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
        }
    }

}
